/*
 * TrayIconControl.java
 *
 * Created on 31 March 2007, 11:47
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package fasea.ui.search;

import fasea.ui.utils.ImageControl;
import fasea.ui.*;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import fasea.constants.Constants;
import fasea.utils.Updater;
import java.awt.*;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

/**
 *
 * @author gvasil
 */
public class TrayIconControl {

    private final SystemTray tray;
    private final TrayIcon trayIcon;
    private ImageControl imageControl;
    private SearchViewImpl view;

    public TrayIconControl(SearchViewImpl view) throws UnsupportedOperationException {

        this.imageControl = ImageControl.getImageControl();

        this.tray = SystemTray.getSystemTray();

        PopupMenu popup = new PopupMenu();

        popup.add(createExitTrayIcon());
        popup.add(createHelpTrayIcon());
        popup.add(createUpdateTryIcon());
        popup.add(createAboutTrayItem());


        this.trayIcon = new TrayIcon(imageControl.getTrayIcon(),
                Constants.getApplicationName() + " Desktop "
                + "Search ", popup);

        this.view = view;
    }

    private MenuItem createUpdateTryIcon() {
        ActionListener helpListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                String errorMessage = null;
                boolean updated = true;

                view.setCursor(new Cursor(Cursor.WAIT_CURSOR));

                Updater update = new Updater();

                try {
                    updated = update.isUpdated();
                } catch (UnknownHostException ex) {
                    errorMessage = ex.getMessage();
                } catch (IOException ex) {
                    errorMessage = ex.getMessage();
                } catch (Exception ex) {
                    errorMessage = ex.getMessage();
                }

                view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

                if (errorMessage != null) {
                    JOptionPane.showMessageDialog(view,
                            "<html>"
                            + "There were problems checking for, downloading or installing <br/>"
                            + "this update. Fasea could not be updated because:<br/><br/><b>"
                            + errorMessage + "</b><br/><br/>"
                            + "You can update Fasea manually by visiting this link and <br/>"
                            + "downloading the latest version:<p align=\"center\">"
                            + "<a href=\"" + Constants.getApplicationWebsite() + "\">"
                            + Constants.getApplicationWebsite()
                            + "</p></a><br/></html>",
                            "Update Error", JOptionPane.ERROR_MESSAGE,
                            imageControl.getErrorIcon());
                    return;
                }

                if (updated == false) {
                    JOptionPane.showMessageDialog(view,
                            "<html>"
                            + "The Fasea version that is currently running appears to be old. <br/><br/>"
                            + "You can update Fasea manually by visiting this link and <br/>"
                            + "downloading the latest version:<p align=\"center\">"
                            + "<a href=\"" + Constants.getApplicationWebsite() + "\">"
                            + Constants.getApplicationWebsite()
                            + "</p></a><br/></html>",
                            "Update found", JOptionPane.INFORMATION_MESSAGE,
                            imageControl.getUpdateIcon());
                    return;

                } else {
                    JOptionPane.showMessageDialog(view,
                            "There are no updates available.",
                            "No Updates Found", JOptionPane.INFORMATION_MESSAGE,
                            imageControl.getInfoIcon());
                    return;
                }
            }
        };
        MenuItem helpItem = new MenuItem("Update");
        helpItem.addActionListener(helpListener);
        return helpItem;

    }

    private MenuItem createHelpTrayIcon() {

        ActionListener helpListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JFrame helpFrame = new net.sourceforge.helpgui.gui.MainFrame("/help/", "plastic");
                helpFrame.setTitle("Fasea Help");
                helpFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().
                        getResource("/16x16/help.png")));
                helpFrame.setVisible(true);
            }
        };
        MenuItem helpItem = new MenuItem("Help " + Constants.getApplicationName());
        helpItem.addActionListener(helpListener);
        return helpItem;
    }

    private MenuItem createAboutTrayItem() throws HeadlessException {
        ActionListener aboutListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                AboutPanel panel = new AboutPanel();

                JDialog dialog = new JDialog(view, "About", true);

                dialog.setIconImage(
                        Toolkit.getDefaultToolkit().getImage(getClass().
                        getResource("/help-about.png")));

                dialog.getContentPane().add(panel);
                dialog.pack();
                dialog.setLocationRelativeTo(view);
                dialog.setResizable(false);
                dialog.setVisible(true);
            }
        };
        MenuItem aboutItem = new MenuItem("About");
        aboutItem.addActionListener(aboutListener);
        return aboutItem;
    }

    private MenuItem createExitTrayIcon() throws HeadlessException {
        ActionListener exitListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                view.close();
                tray.remove(trayIcon);
            }
        };

        MenuItem exitItem = new MenuItem("Exit");
        exitItem.addActionListener(exitListener);
        return exitItem;
    }

    public void add() {
        if (SystemTray.isSupported()) {

            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {
                }

                public void mouseEntered(MouseEvent e) {
                }

                public void mouseExited(MouseEvent e) {
                }

                public void mousePressed(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        if (!view.isVisible()) {
                            view.setVisible(true);
                            view.setState(java.awt.Frame.NORMAL);
                        }
                    }
                }

                public void mouseReleased(MouseEvent e) {
                }
            };
            this.trayIcon.setImageAutoSize(true);
            this.trayIcon.addMouseListener(mouseListener);

            //    Depending on which Mustang build you have, you may need to uncomment
            //    out the following code to check for an AWTException when you add 
            //    an image to the system tray.

            try {
                this.tray.add(this.trayIcon);
                this.view.setVisible(false);
            } catch (java.awt.AWTException e) {
                System.err.println("TrayIcon could not be added.");
            }
        } else {
            System.err.println("System tray is currently not supported.");
        }
    }

    public void displayMessage(String caption, String text, TrayIcon.MessageType type) {
        trayIcon.displayMessage(caption, text, type);
    }

    public void setToolTip(String text) {
        this.trayIcon.setToolTip(text);
    }
}
